<?php
/**
 * 附件函数库
 * @authors moufer(moufer@163.com)
 * @date    2015-01-02 21:59:54
 * @version $Id$
 */

class ms_attachment extends ms_base {
    
    /**
     * 通过内部规范化的文件路径获得一个用于网页可访问的URL地址
     * @param  string  $path_exp 内部规范化的文件路径表达式
     * @param  boolean $full 是否显示完整路径
     * @return string
     */
    public static function file_url($path_exp, $full_url = true)
    {
	    if(!$path_exp) return '';
	    if(!$full) return URLROOT.'/'.$path_exp;
	    return trim(S('siteurl'),'/').'/'.$path_exp;
	}

	/**
	 * 删除一个附件文件文件
	 * @param  string $path_exp 内部规范化的文件路径表达式
	 * @return boolean
	 */
	public static function delete_file($path_exp, $is_full_path = false)
	{
		if(!$path_exp || strlen($path_exp) < 10) return false;
		$filepath = (!$is_full_path?MUDDER_ROOT:'').str_replace('/', DS, $path_exp);
		if(is_file($filepath)) return @unlink(str_replace('/', DS, $filepath));
		return false;
	}


	public static function create_dir($root_dir_name, $sub_dir_mod, $path_exp = null)
	{
		//二级目录结构设置
		if($sub_dir_mod == 'WEEK') {
			$sub_dir = date('Y', _G('timestamp')).'-week-'.date('W', _G('timestamp'));
		} elseif($sub_dir_mod == 'DAY') {
			$sub_dir = date('Y-m-d', _G('timestamp'));
		} elseif($sub_dir_mod == 'MONTH' || !$sub_dir_mod) {
			$sub_dir = date('Y-m', _G('timestamp'));
		}
		$dir = trim(str_replace(array('/','\\'), DS, $root_dir_name.DS.$sub_dir),DS);
		if(!$dir) return false;
		//二级目录存在判断和生成
		if($dir) {
			$full_path = $path = '';
			$dir_list = explode(DS, $dir);
			foreach ($dir_list as $d) {
				$path .= DS.$d;
				$full_path = MUDDER_UPLOAD.trim($path,DS);
				if(!@is_dir($full_path)) {
					if(!@mkdir($full_path, 0777)) {
						show_error(lang('global_mkdir_no_access', str_replace(MUDDER_ROOT,'',$full_path)));
					}
				}
			}
		}
		$path = str_replace(DS, '/', str_replace(MUDDER_ROOT, '', $full_path));
		return $path;
	}

}

/** end */